package com.android.xk.mask

import android.app.ProgressDialog
import android.app.Service
import android.app.smdt.SmdtManager
import android.content.ComponentName
import android.content.Intent
import android.content.ServiceConnection
import android.media.MediaCodec.VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING
import android.net.NetworkInfo
import android.os.Bundle
import android.os.IBinder
import android.provider.Settings
import androidx.appcompat.app.AppCompatActivity
import com.android.xk.mask.client.SocketClient
import com.android.xk.mask.event.MessageEvent
import com.android.xk.mask.event.TransparentEvent
import com.android.xk.mask.guard.LocalService
import com.android.xk.mask.model.*
import com.android.xk.mask.serialPort.SerialPort
import com.android.xk.mask.serialPort.StickPackageHelper
import com.android.xk.mask.view.FullVideoView
import com.apkfuns.logutils.LogUtils
import com.facebook.drawee.view.SimpleDraweeView
import com.fatangare.logcatviewer.utils.LogcatViewer
import com.github.pwittchen.reactivenetwork.library.rx2.ReactiveNetwork
import com.stericson.RootShell.execution.Command
import com.stericson.RootTools.RootTools
import com.vicpin.krealmextensions.delete
import com.vicpin.krealmextensions.query
import com.vicpin.krealmextensions.save
import com.yanzhenjie.kalle.Kalle
import com.yanzhenjie.kalle.download.Callback
import com.youth.banner.Banner
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.activity_main.*
import org.simple.eventbus.EventBus
import org.simple.eventbus.Subscriber
import tp.xmaihh.serialport.bean.ComBean

class MainActivity : AppCompatActivity(), SerialPort.OnDataReceivedListener
{

    private val qrImage by lazy { findViewById<SimpleDraweeView>(R.id.qr_image) }

    private val banner by lazy {
        findViewById<Banner>(R.id.banner).apply {
            setImageLoader(PicassoImageLoader())
            setOnBannerListener {

            }
        }
    }

    private val videoView by lazy {
        findViewById<FullVideoView>(R.id.videoView).apply {
            setOnPreparedListener {
                it.setVideoScalingMode(VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING)
                it.start()
            }
        }
    }

    private var videoIndex = 0

    @ExperimentalStdlibApi
    override fun onDataReceived(paramComBean: ComBean?)
    {
        paramComBean?.let {
            LogUtils.i("接收串口数据 ${it.bRec.joinToString(" ") {
                String.format("%02x", (it.toInt() and 0xFF))
            }
            }")
//            SocketClient.send(it.bRec)
//            if (it.bRec.size > 12) {
////                Unpooled.buffer().writeBytes(it.bRec)
//                val len = it.bRec[12].toInt()
//                if (it.bRec[0] == 0x7e.toByte() && it.bRec[1] == 0x0f.toByte()) {
//                    if (it.bRec.size == len + 12) {
//                        SocketClient.send(it.bRec)
//                    }else
//                    {
//                        Unpooled.buffer().writeBytes(it.bRec)
//                    }
//                }
//
//            }

            if (it.bRec[2] == 0xaa.toByte() && it.bRec[3] == 0x55.toByte() && App.deviceId == null)
            {
                App.deviceId = it.bRec.copyOfRange(4, 12).toHex()
            }


//            val buff = ByteArray(it.bRec.size + 2)
//            buff[0] = 0x7e
//            buff[1] = 0x0f
//
//            for (i in it.bRec.indices)
//            {
//                buff[i + 2] = it.bRec[i]
//            }



            SocketClient.send(it.bRec)
        }
    }


    private val mSerialPort by lazy {
        SerialPort("/dev/ttyS2", 19200, this).apply {
            stickPackageHelper = StickPackageHelper()
        }
    }
    private var netDisposable: Disposable? = null

    override fun onCreate(savedInstanceState: Bundle?)
    {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        EventBus.getDefault().register(this)
        netDisposable = ReactiveNetwork.observeNetworkConnectivity(this)
                .filter { it.state() == NetworkInfo.State.CONNECTED }
                .onIO()
                .subscribe {
                    SocketClient.connect(serverIp, port)
                }
        try
        {
            mSerialPort.open()
        }
        catch (e: Exception)
        {
            e.printStackTrace()
        }


        //获取视频

        startPlayVideo()
        startPlayImages()
        displayQr()
        qrImage.setOnLongClickListener {
            startActivity(Intent(Settings.ACTION_SETTINGS))
            true
        }

        button.setOnLongClickListener {

            //            downloadApp(AppUpdate().apply {
//                operateType = 2
//                appUrl = "http://file.kuaixing.vip/group1/default/20191122/10/47/4/app-debug.apk"
//            })
            LogcatViewer.showLogcatLoggerView(this)
//            SmdtManager.create(applicationContext)
//                .smdtSilentInstall("/sdcard/Download/app.apk", applicationContext)
            true
        }

        bindService(Intent(this, LocalService::class.java), connection, Service.BIND_AUTO_CREATE)
    }

    private var guardBinder: IGuardInterface? = null

    private val connection = object : ServiceConnection
    {
        override fun onServiceDisconnected(name: ComponentName?)
        {
            LogUtils.i("远程服务器断开")
        }

        override fun onServiceConnected(name: ComponentName?, service: IBinder?)
        {
            guardBinder = IGuardInterface.Stub.asInterface(service)
            LogUtils.e("服务启动成功")
//            try {
//                LogUtils.e("LocalService connected with ${guardBinder?.serviceName}")
////                guardBinder?.appUpdate("", 1)
//
//            } catch (e: java.lang.Exception) {
//                e.printStackTrace()
//            }
        }

    }

    private var sequence = 0

    private fun startPlayVideo()
    {
        try
        {
            val videoList = Ad().query { equalTo("displayArea", 1.toByte()).sort("displayIndex") }
//                Realm.getDefaultInstance().where(Ad::class.java).equalTo("displayArea", 1.toByte())
//                    .sort("displayIndex").findAll()
            if (videoList.isNotEmpty())
            {
                videoView.setOnCompletionListener {
                    videoIndex += 1
                    if (videoIndex == videoList.size)
                    {
                        videoIndex = 0
                    }
                    videoView.setOnErrorListener { mp, what, extra ->
                        startPlayVideo()
                        true
                    }

                    val res = videoList[videoIndex]
                    startPlay(res.resourceUrl)
                    if (App.deviceId != null)
                    {
                        val msg = Message().apply {
                            msgLen = 66
                            msgId = 0x0F000005
                            deviceId = App.deviceId!!
                            sequence = this@MainActivity.sequence++
                        }

                        msg.userData = DataPost().apply {
                            displayArea = res.displayArea.toInt()
                            resoureId = res.resourceId
                            timeType = 1
                            time = getCurrentDateString()
                        }

                        SocketClient.send(msg)
                    }


                }
                startPlay(videoList[videoIndex].resourceUrl)
            }
        }
        catch (e: Exception)
        {
            e.printStackTrace()
        }

    }

    private fun startPlay(url: String?)
    {
        url?.let {
            videoView.setVideoPath(
                    App.getProxy(this).getProxyUrl(
                            it,
                            true
                    )
            )
        }

//        videoView.start()
    }

    private fun startPlayImages()
    {
        val imageList = Ad().query { equalTo("displayArea", 2.toByte()).sort("displayIndex") }
        if (imageList.isNotEmpty())
        {
            val urls = imageList.map { it.resourceUrl }
            banner.setImages(urls)
            banner.start()
        }
    }

    private fun displayQr()
    {
        Ad().query {
            equalTo("displayArea", 3.toByte())
                    .findFirst()?.let {
                        qrImage.setImageURI(it.resourceUrl)
                    }
        }
    }

    override fun onDestroy()
    {
        EventBus.getDefault().unregister(this)
        netDisposable?.dispose()
        super.onDestroy()
    }


    @Subscriber
    fun onTransparent(event: TransparentEvent)
    {
        LogUtils.e("发送串口数据 ${event.data.toHex()}")
        mSerialPort.send(event.data)
    }

    @Subscriber
    fun onMessageReceived(event: MessageEvent)
    {
        LogUtils.e(event.msg)

        when (event.msg.msgId)
        {
            0x0F000001 ->
            {
                sendResponseMsg(event.msg, 0x0F000002, 0)
                val ad = event.msg.userData as Ad

                when (ad.operateType.toInt())
                {
                    1, 3 ->
                    {
                        ad.save()
                    }
                    2    ->
                    {
                        ad.delete { equalTo("resourceId", ad.resourceId) }
                    }
                }

                when (ad.displayArea.toInt())
                {
                    1 -> startPlayVideo()
                    2 -> startPlayImages()
                    3 -> displayQr()
                }
            }
            0x0F000007 ->
            {
                sendResponseMsg(event.msg, 0x0F000008, 0)
                val appUpdate = event.msg.userData as AppUpdate
                if (appUpdate.operateType != 3)
                {
                    downloadApp(appUpdate)
                }
                else
                {
                    RootTools.getShell(true).add(Command(0, "pm uninstall $packageName"))
                }
            }
            0x0F000009 ->
            {
                sendResponseMsg(event.msg, 0x0F000010, 0)
                val switchgear = event.msg.userData as Switchgear
                when (switchgear.operateType)
                {
                    2 -> SmdtManager.create(this).shutDown()
                    3 -> SmdtManager.create(this).smdtReboot()
                }
            }
            0x0F000011 ->
            {
                sendResponseMsg(event.msg, 0x0F000012, 0)
                LogUtils.i("收到配置设备的参数 ${event.msg}")
            }
        }
    }


    private fun sendResponseMsg(msg: Message, messageId: Int, res: Int)
    {
        val response = Message().apply {
            msgLen = 46
            msgId = messageId
            version = msg.version
            sequence = msg.sequence
            deviceId = msg.deviceId
            userData = MessageResult().apply {
                result = res
                errorCode = 0
            }
        }
        SocketClient.send(response)
    }

    /**
     * 下载App
     */
    private fun downloadApp(appUpdate: AppUpdate)
    {

        var dialog: ProgressDialog? = null

        Kalle.Download.get(appUpdate.appUrl)
                .directory("/sdcard/Download")
                .fileName("app.apk")
                .onProgress { progress, byteCount, speed ->
                    dialog?.progress = progress
                }
                .perform(object : Callback
                {
                    override fun onFinish(path: String)
                    {
                        dialog?.setTitle("正在安装程序...")
                        LogUtils.e("安装程序 $path")
                        SmdtManager.create(this@MainActivity)
                                .smdtSilentInstall(path, this@MainActivity)
                    }

                    override fun onCancel()
                    {
                    }

                    override fun onException(e: java.lang.Exception)
                    {
                        e.printStackTrace()
                    }

                    override fun onEnd()
                    {
                    }

                    override fun onStart()
                    {
                        dialog = ProgressDialog(this@MainActivity).apply {
                            setTitle("正在下载更能文件...")
                            setCanceledOnTouchOutside(false)
                            setProgressStyle(ProgressDialog.STYLE_HORIZONTAL)
                            max = 100
                        }
                        dialog?.show()
                    }
                })
    }


}
